<template>
  <AdvanceQuery
    class="form-script-manage"
    ref="scriptForm"
    :height="mainContextHeight"
    :treePanel="groupConfig"
    :tablePanel="listConfig"
    @editGroupItem="onEditGroup"
    @deleteGroupItem="onDeleteGroup"
    @refreshTable="onRefreshApiTable"
    @addTableItem="onEditApiForm()"
  >
    <template #table>
      <table-box
        :data="apiTableWidget.dataList"
        :size="layoutStore.defaultFormItemSize"
        header-cell-class-name="table-header-gray"
        height="auto"
        :hasExtend="false"
        :seq-config="{
          startIndex: (apiTableWidget.currentPage - 1) * apiTableWidget.pageSize,
        }"
        style="padding-bottom: 16px"
      >
        <vxe-column title="序号" type="seq" width="50px" :index="apiTableWidget.getTableIndex" />
        <vxe-column title="脚本名称" field="apiName" />
        <vxe-column title="脚本编码" field="apiCode" />
        <vxe-column title="脚本描述" field="apiDesc" />
        <vxe-column title="创建时间" field="createTime">
          <template v-slot="scope">
            {{ formatDateByStatsType(scope.row.createTime, 'datetime') }}
          </template>
        </vxe-column>
        <vxe-column title="操作" fixed="right" width="180">
          <template v-slot="scope">
            <el-button
              link
              type="primary"
              :size="layoutStore.defaultFormItemSize"
              @click="onEditApiForm(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              link
              type="primary"
              :size="layoutStore.defaultFormItemSize"
              @click="onEditApiScript(scope.row)"
            >
              编辑脚本
            </el-button>
            <el-button
              link
              type="danger"
              :size="layoutStore.defaultFormItemSize"
              @click="onDeleteApiForm(scope.row)"
            >
              删除
            </el-button>
          </template>
        </vxe-column>
        <template #pagination>
          <el-row type="flex" justify="end" style="padding-top: 20px; height: 70px">
            <el-pagination
              :total="apiTableWidget.totalCount"
              :current-page="apiTableWidget.currentPage"
              :page-size="apiTableWidget.pageSize"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, prev, pager, next, sizes"
              @current-change="apiTableWidget.onCurrentPageChange"
              @size-change="apiTableWidget.onPageSizeChange"
            >
            </el-pagination>
          </el-row>
        </template>
      </table-box>
    </template>
  </AdvanceQuery>
</template>

<script setup lang="ts">
import { reactive, ref, inject, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus, EditPen, Edit, Delete } from '@element-plus/icons-vue';
import { ANY_OBJECT } from '@/types/generic';
import { Dialog } from '@/components/Dialog';
import { useTable } from '@/common/hooks/useTable';
import { TableOptions } from '@/common/types/pagination';
import { useDate } from '@/common/hooks/useDate';
import { useLayoutStore } from '@/store';
import { OnlineApi, OnlineApiGroup } from '@/types/online/script';
import OnlineApiController from '@/api/online/OnlineApiController';
import OnlineApiGroupController from '@/api/online/OnlineApiGroupController';
import AdvanceQuery from '@/components/AdvanceQuery/index.vue';
import EditApiGroup from './editApiGroup.vue';
import EditApiForm from './editApiForm.vue';
import EditApiScript from './editApiScript.vue';

const layoutStore = useLayoutStore();
const { formatDateByStatsType } = useDate();
const mainContextHeight = inject('mainContextHeight', 200);

const scriptForm = ref();
const listConfig = {
  title: '脚本列表',
  supportAdd: true,
  addText: '新建脚本',
};

const apiGroupList = ref<OnlineApiGroup[]>([]);
const currentGroup = ref<OnlineApiGroup>();

// 加载Api分组数据
const loadApiGroupData = () => {
  return new Promise<OnlineApiGroup[]>((resolve, reject) => {
    OnlineApiGroupController.list({})
      .then(res => {
        apiGroupList.value = res.data;
        resolve(res.data);
      })
      .catch(e => {
        console.warn(e);
      });
  });
};

const groupConfig = {
  title: '脚本分组',
  supportAdd: true,
  supportEdit: true,
  supportDelete: true,
  addText: '新建分组',
  keyColumnName: 'groupId',
  nameColumnName: 'groupName',
  loadFunction: loadApiGroupData,
};

// 加载API数据
const loadApplyData = (params: ANY_OBJECT) => {
  return new Promise<{ dataList: OnlineApi[]; totalCount: number }>((resolve, reject) => {
    if (params == null) params = {};
    // 添加分组过滤
    if (currentGroup.value) {
      params.onlineApiDtoFilter = {
        ...params.onlineApiDtoFilter,
        groupId: currentGroup.value.groupId,
      };
    }
    OnlineApiController.list(params)
      .then(res => {
        resolve({
          dataList: res.data.dataList,
          totalCount: res.data.totalCount,
        });
      })
      .catch(e => {
        reject(e);
      });
  });
};

const tableOptions: TableOptions<OnlineApi> = {
  loadTableData: loadApplyData,
  verifyTableParameter: () => true,
  paged: true,
  orderFieldName: 'createTime',
  ascending: false,
};

const apiTableWidget = reactive(useTable(tableOptions));

// 编辑API分组
const onEditGroup = (row: ANY_OBJECT) => {
  const groupData = row as OnlineApiGroup;
  Dialog.show(
    groupData ? '编辑分组' : '新建分组',
    EditApiGroup,
    {
      area: ['500px'],
    },
    {
      groupId: (groupData || {}).groupId,
    },
  )
    .then(() => {
      scriptForm.value.refreshGroup();
    })
    .catch(e => {
      console.warn(e);
    });
};

// 删除API分组
const onDeleteGroup = (row: ANY_OBJECT) => {
  const groupData = row as OnlineApiGroup;
  ElMessageBox.confirm('是否删除此分组？', '', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      return OnlineApiGroupController.delete({
        groupId: row.groupId,
      });
    })
    .then(() => {
      ElMessage.success('删除成功！');
      scriptForm.value.refreshGroup();
    })
    .catch(e => {
      console.warn(e);
    });
};

// 删除API
const onDeleteApiForm = (row: OnlineApi) => {
  ElMessageBox.confirm('是否删除此脚本？', '', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      return OnlineApiController.delete({
        id: row.id,
      });
    })
    .then(() => {
      ElMessage.success('删除成功！');
      apiTableWidget.refreshTable();
    })
    .catch(e => {
      console.warn(e);
    });
};

// 编辑API
const onEditApiForm = (row?: OnlineApi | null) => {
  Dialog.show(
    row ? '编辑脚本' : '新建脚本',
    EditApiForm,
    {
      area: ['800px'],
    },
    {
      id: (row || {}).id,
      rowData: row || null,
      groupId: currentGroup.value?.groupId,
      groupList: apiGroupList.value,
    },
  )
    .then(() => {
      apiTableWidget.refreshTable();
    })
    .catch(e => {
      console.warn(e);
    });
};

// 编辑脚本内容
const onEditApiScript = (row: OnlineApi) => {
  Dialog.show(
    '编辑脚本内容',
    EditApiScript,
    {
      area: ['1200px', '880px'],
    },
    {
      formData: row,
      onSaveScript: (script: string) => {
        row.apiScript = script;
      },
    },
  ).catch(e => {
    console.warn(e);
  });
};

const onRefreshApiTable = (category: ANY_OBJECT) => {
  currentGroup.value = category as OnlineApiGroup;
  apiTableWidget.refreshTable(true, 1);
};

onMounted(() => {
  // loadApiGroupData();
});
</script>

<style scoped>
.form-script-manage {
  height: 100%;
}
</style>
